#include "Camera.h"

#include <Windows.h>
#include <SDL.h>
#include <gl\GL.h>
#include <cmath>
#include "KeyManager.h"

#ifndef M_PI 
#define M_PI 3.1452392
#endif

extern bool appRunning;

Camera::Camera()
{
	yawAngle = 0.0f;
	pitchAngle = 0.0f;
	x = 0.0f;
	y = 0.0f;
	z = 0.0f;
}

void Camera::init(float x, float y, float z)
{
	this->x = x;
	this->y = y;
	this->z = z;
}

void Camera::rotate()
{
	int midX = 320;
	int midY = 240;

	SDL_ShowCursor(SDL_DISABLE);

	int curX;
	int curY;

	SDL_GetMouseState(&curX, &curY);

	int deltaX = curX - midX;
	int deltaY = curY - midY;
	
	yawAngle += (float)deltaX * 0.05f;
	pitchAngle += (float)deltaY * 0.05f;

	if(pitchAngle > 80.0f)
		pitchAngle = 80.0f;
	
	if(pitchAngle < -80.0f)
		pitchAngle = -80.0f;

	if (yawAngle > 360.0)
		yawAngle -= 360.0;

	if (yawAngle < 0.0)
		yawAngle += 360.0;

	SDL_WarpMouse(midX, midY);

	glRotatef(pitchAngle, 1.0f, 0.0f, 0.0f);
	glRotatef(yawAngle, 0.0f, 1.0f, 0.0f);
}

void Camera::move()
{
	if (KeyManager::get()->isKeyDown(GKEY_UP) || KeyManager::get()->isKeyDown(GKEY_W))
	{
		x += (float)(sin(yawAngle * M_PI/180) * 0.4);
		z -= (float)(cos(yawAngle * M_PI/180) * 0.4);
	}
	else if (KeyManager::get()->isKeyDown(GKEY_DOWN) || KeyManager::get()->isKeyDown(GKEY_S))
	{
		x += (float)(sin((yawAngle+180.0) * M_PI/180) * 0.4);
		z -= (float)(cos((yawAngle+180.0) * M_PI/180) * 0.4);
	}

	if (KeyManager::get()->isKeyDown(GKEY_LEFT) || KeyManager::get()->isKeyDown(GKEY_A))
	{
		x += (float)(sin((yawAngle-90.0f) * M_PI/180) * 0.2);
		z -= (float)(cos((yawAngle-90.0f) * M_PI/180) * 0.2);
	}
	else if (KeyManager::get()->isKeyDown(GKEY_RIGHT) || KeyManager::get()->isKeyDown(GKEY_D))
	{
		x += (float)(sin((yawAngle+90.0f) * M_PI/180) * 0.2);
		z -= (float)(cos((yawAngle+90.0f) * M_PI/180) * 0.2);
	}
	else if (KeyManager::get()->isKeyDown(GKEY_B))
	{
		y += 0.1f;
	}
	else if (KeyManager::get()->isKeyDown(GKEY_N))
	{
		y -= 0.1f;
	}
	else if (KeyManager::get()->isKeyDown(GKEY_P))
	{
		appRunning = false;
	}

	glTranslatef(-x, -y, -z);
}

//Vec3f Camera::getPosition()
//{
//	return Vec3f(x, y, z);
//}
//	
//Vec3f Camera::getDirection()
//{
//	return Vec3f(-cos(pitchAngle*M_PI/180.0)*sin(yawAngle*M_PI/180.0), 
//		sin(pitchAngle*M_PI/180.0), -cos(pitchAngle*M_PI/180.0)*cos(yawAngle*M_PI/180.0));
//}

float Camera::getYaw()
{
	return yawAngle;
}

float Camera::getPitch()
{
	return pitchAngle;
}